import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { toolchain } from "../toolchain.js";

export class ProjectHelper {
    public static async readKeepCfg(keepMap: { [file: string]: string }, usedByCfgMap: { [icon: string]: string }): Promise<void> {
        if (toolchain.opts.cfg != null) {
            const assetsRoot = path.join(toolchain.opts.projectRoot, 'Assets/AssetSources');
        
            // 部分写死保留的prefab
            if (toolchain.opts.cfg.keep != null) {
                for (const k of toolchain.opts.cfg.keep) {
                    const keeps = await fg(k, { cwd: toolchain.opts.projectRoot });
                    for (const f of keeps) {
                        keepMap[path.normalize(f)] = k;
                    }
                }
            }

            // 读入表格使用的模型
            if (toolchain.opts.cfg.iconCfg != null) {
                for (const ic of toolchain.opts.cfg.iconCfg) {
                    if (ic.disabled) continue;
                    for (const rule of ic.rules) {
                        const cf = path.join(assetsRoot, 'data', rule.cfgFile);
                        if (!fs.existsSync(cf)) {
                            console.error('cfg file not eixsts:', cf);
                            continue;
                        }
                        const cfgs = await fs.readJson(cf);
                        for (const c of cfgs) {
                            const v = c[rule.cfgKey];
                            const varr = v instanceof Array ? v : [v];
                            for (const vv of varr) {
                                const p = ic.path.replaceAll('*', vv).toLowerCase();
                                const k = `${rule.cfgFile}:${rule.cfgKey}`;
                                usedByCfgMap[p] = k;
                                usedByCfgMap[p.replace('.png', '_b.png')] = k;
                                // 部分图标还加了职业后缀
                                usedByCfgMap[p.replace('.png', '_1.png')] = k;
                                usedByCfgMap[p.replace('.png', '_2.png')] = k;
                                usedByCfgMap[p.replace('.png', '_3.png')] = k;                                
                            }
                        }
                    }
                }
            }
        } else {
            console.error('no cfg!');
            process.exit(1);
        }
    }
}